package com.imooc.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

/**
 * Created by zghgchao 2017/12/29 13:56
 * JDBCUtil工具类：
 * 1）获取Connection
 * 2）释放资源
 */
public class JDBCUtil {

//    private static final String USERNAME = "root";
//    private static final String PASSWORD = "root";
//    private static final String DRIVERCLASS = "com.mysql.jdbc.Driver";
//    private static final String URL = "jdbc:mysql://172.17.66.51:3306/spring_data";


    /**
     * 数据库连接
     * 1）获取Connection
     *
     * @return
     */
    public static Connection getConnection() throws Exception {
        InputStream inputStream = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
        Properties properties = new Properties();
        properties.load(inputStream);

        String USERNAME = properties.getProperty("jdbc.user");
        String PASSWORD = properties.getProperty("jdbc.password");
        String DRIVERCLASS = properties.getProperty("jdbc.driver");
        String URL = properties.getProperty("jdbc.url");

        Connection connection = null;

        try {
            Class.forName(DRIVERCLASS);

            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("--------------数据库连接异常-------------");
        }
        System.out.println("--------------数据库连接成功-------------");
        return connection;
    }

    /**
     * 释放资源
     *
     * @param connection
     * @param patmt
     * @param rs
     */
    public static void release(Connection connection, PreparedStatement patmt, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("--------------ResultSet关闭异常-------------");
            }
        }
        if (patmt != null) {
            try {
                patmt.close();
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("--------------PreparedStatement关闭异常-------------");
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("--------------Connection关闭异常-------------");
            }
        }
        System.out.println("--------------数据库资源已关闭-------------");
    }
}
